<!--
 * @Description: 返单
 * 
 * @Author: XiongYaoYuan<xiongyaoyuan>
 * @Date: 2023-06-23 15:37:13
 * @FilePath: /yuxiuproweb/src/views/mes/pro/workorder/split/index.vue
-->
<template>
  <el-drawer title="订单返单" size="100%" :visible.sync="shows">
    <template #title>
      <div style="display: flex; align-items: center">
        <span>订单返单</span>
        <el-button
          type="success"
          size="mini"
          class="ml20"
          icon="el-icon-download"
          @click="handleDownload"
          >生成图片</el-button
        >
      </div>
    </template>
    <div class="split-view" id="printPDF" v-if="orderInfo">
      <el-descriptions class="margin-top split-descriptions" :column="4" border>
        <el-descriptions-item
          >订单编号：{{ orderInfo.orderNo }}
        </el-descriptions-item>
        <el-descriptions-item>
          下单时间：{{ parseTime(orderInfo.orderDate, "{y}-{m}-{d}") }}
        </el-descriptions-item>
        <el-descriptions-item>
          完成时间：{{ parseTime(orderInfo.deliveryTime, "{y}-{m}-{d}") }}
        </el-descriptions-item>
        <el-descriptions-item>
          客服：{{ orderInfo.customerService }}</el-descriptions-item
        >
        <el-descriptions-item>
          客户名称：{{ orderInfo.clientName }}
        </el-descriptions-item>
        <el-descriptions-item>
          联系方式：{{ orderInfo.clientContactInformation }}
        </el-descriptions-item>
        <el-descriptions-item>
          收货地址：{{ orderInfo.clientAddress }}
        </el-descriptions-item>
        <el-descriptions-item>
          备注信息：{{ orderInfo.remark }}
        </el-descriptions-item>
        <el-descriptions-item>
          付款方式：{{ orderInfo.logisticsPaymentMethod }}
        </el-descriptions-item>
        <el-descriptions-item>
          物流公司：{{ orderInfo.logisticsCompany }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- <el-table :data="productProcessList" class="mt20" v-if="type">
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column label="工序" prop="processName"></el-table-column>
        <el-table-column label="完成时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作人" prop="updateBy"></el-table-column>
      </el-table> -->

      <el-collapse class="mt20 drawer-collapse" v-model="activeNames">
        <CLView v-if="tableData.length" :list="tableData" :type="type" />
        <CMView v-if="cmTableData.length" :list="cmTableData" :type="type" />
        <QTView v-if="qtTableData.length" :list="qtTableData" :type="type" />
        <CPYLView
          v-if="cpylTableData.length"
          :list="cpylTableData"
          :type="type"
        />
      </el-collapse>

      <el-descriptions
        class="margin-top split-descriptions mt20 mb20"
        :column="2"
        border
      >
        <el-descriptions-item>
          <span style="font-size: 16px; font-weight: bold; color: red">
            其他费用：{{ orderInfo.otherExpenses }}
          </span>
        </el-descriptions-item>
        <!-- <el-descriptions-item> 邮费： 0元整单调价： 0元 </el-descriptions-item> -->
        <el-descriptions-item>
          <span style="font-size: 18px; font-weight: bold; color: red">
            总计：{{ orderInfo.totalPrice }}元
          </span>
        </el-descriptions-item>
        <el-descriptions-item>
          <span style="font-size: 16px; font-weight: bold; color: red">
            温馨提示：
            2.8门幅定宽做，单色对开宽度超过2.7，单开宽度超过1.4会有坚拼缝，部分型号定高定宽都可以做，但是纹路会发生变化，请您根据需求下单。（面料深浅色遮光率相差较大，资料标注遮光率为参考值以版本面料实物为准）
          </span>
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </el-drawer>
</template>

<script>
import { getCustomerOrderInfo } from "@/api/asc/order";
import { getDetailList } from "@/api/asc/curtain";
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
import CLView from "./cl.vue";
import CMView from "./cm.vue";
import QTView from "./qt.vue";
import CPYLView from "./cpyl.vue";
import { productProcess } from "@/api/asc/split";

export default {
  dicts: [
    "order_curtain_section",
    "md_complex_machining_model_part_1",
    "md_complex_machining_model_part_2",
  ],
  components: {
    CLView,
    CMView,
    QTView,
    CPYLView,
  },
  props: {
    show: Boolean,
    data: {
      type: Object,
    },
    type: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      activeNames: ["1", "2", "3", "4"],
      tableData: [],
      cmTableData: [],
      qtTableData: [],
      cpylTableData: [],
      productProcessList: [],
      orderInfo: null,
    };
  },
  computed: {
    shows: {
      get() {
        return this.show;
      },
      set(newValue) {
        this.$emit("update:show", newValue);
      },
    },
  },
  created() {
    this.getCustomerOrderInfo();
    // if (this.type) {
    //   this.productProcess();
    // }
  },
  methods: {
    // productProcess() {
    //   productProcess({
    //     productId: this.data.productId,
    //     type: this.type,
    //   }).then(({ rows }) => {
    //     this.productProcessList = rows || [];
    //   });
    // },
    async handleCLData(data) {
      this.tableData = [];

      const list = await Promise.all(
        data.customCurtainVOList?.map(async (e, i) => {
          const { rows: detailList } = await getDetailList({
            productId: e.productNo,
            type: "0",
          });
          return {
            productNo: e.productNo,
            detailList,
          };
        })
      );

      data.customCurtainVOList.forEach(async (e, i) => {
        const detailList =
          list?.find((w) => w.productNo === e.productNo)?.detailList || [];

        let childList = [];
        if (e.fabricVOList?.length >= detailList.length) {
          childList = e.fabricVOList?.map((w, j) => {
            return {
              ...w,
              price: detailList?.[j]?.price || "",
              subTotal: detailList?.[j]?.subTotal || "",
              priceName: detailList?.[j]?.name || "",
              width: "",
            };
          });
        } else {
          childList = detailList?.map((w, j) => {
            return {
              ...(e.fabricVOList?.[j] ? { ...e.fabricVOList[j] } : {}),
              price: w.price,
              subTotal: w.subTotal,
              priceName: w.name,
              width: "",
            };
          });
        }

        childList.forEach(({ width, ...v }, index) => {
          this.tableData.push({
            ...e,
            ...v,
            i: i + 1,
            begin: index === 0 ? this.tableData.length : null,
            fabricVOList: childList,
          });
        });
      });
    },

    async handleCMData(data) {
      this.cmTableData = [];

      const list = await Promise.all(
        data.customWindowCurtainVOList?.map(async (e, i) => {
          const { rows: detailList } = await getDetailList({
            productId: e.productNo,
            type: "1",
          });
          return {
            productNo: e.productNo,
            detailList,
          };
        })
      );

      data.customWindowCurtainVOList.forEach(async (e, i) => {
        const detailList =
          list?.find((w) => w.productNo === e.productNo)?.detailList || [];

        let childList = [];
        if (e.fabricVOList?.length >= detailList.length) {
          childList = e.fabricVOList?.map((w, j) => {
            return {
              ...w,
              price: detailList?.[j]?.price || "",
              subTotal: detailList?.[j]?.subTotal || "",
              priceName: detailList?.[j]?.name || "",
              width: "",
            };
          });
        } else {
          childList = detailList?.map((w, j) => {
            return {
              ...(e.fabricVOList?.[j] ? { ...e.fabricVOList[j] } : {}),
              price: w.price,
              subTotal: w.subTotal,
              priceName: w.name,
              width: "",
            };
          });
        }

        childList.forEach(({ width, ...v }, index) => {
          this.cmTableData.push({
            ...e,
            ...v,
            i: i + 1,
            begin: index === 0 ? this.cmTableData.length : null,
            fabricVOList: childList,
          });
        });
      });
    },

    async handleQTData(data) {
      this.qtTableData = [];

      const list = await Promise.all(
        data.customOtherVOList?.map(async (e, i) => {
          const { rows: detailList } = await getDetailList({
            productId: e.productNo,
            type: "2",
          });
          return {
            productNo: e.productNo,
            detailList,
          };
        })
      );

      data.customOtherVOList.forEach(async (e, i) => {
        const detailList =
          list?.find((w) => w.productNo === e.productNo)?.detailList || [];

        let childList = [];
        if (e.fabricVOList?.length >= detailList.length) {
          childList = e.fabricVOList?.map((w, j) => {
            return {
              ...w,
              price: detailList?.[j]?.price || "",
              subTotal: detailList?.[j]?.subTotal || "",
              priceName: detailList?.[j]?.name || "",
              width: "",
            };
          });
        } else {
          childList = detailList?.map((w, j) => {
            return {
              ...(e.fabricVOList?.[j] ? { ...e.fabricVOList[j] } : {}),
              price: w.price,
              subTotal: w.subTotal,
              priceName: w.name,
              width: "",
            };
          });
        }

        childList.forEach(({ width, ...v }, index) => {
          this.qtTableData.push({
            ...e,
            ...v,
            i: i + 1,
            begin: index === 0 ? this.qtTableData.length : null,
            fabricVOList: childList,
          });
        });
      });
    },

    async handleCPYLData(data) {
      this.cpylTableData = [];

      const list = await Promise.all(
        data.rawVOList?.map(async (e, i) => {
          const { rows: detailList } = await getDetailList({
            productId: e.productNo,
            type: "3",
          });
          return {
            productNo: e.productNo,
            detailList,
          };
        })
      );

      data.rawVOList.forEach(async (e, i) => {
        const detailList =
          list?.find((w) => w.productNo === e.productNo)?.detailList || [];

        let childList = [];
        childList = detailList?.map((w, j) => {
          return {
            ...(e.fabricVOList?.[j] ? { ...e.fabricVOList[j] } : {}),
            price: w.price,
            subTotal: w.subTotal,
            priceName: w.name,
            width: "",
          };
        });

        childList.forEach(({ width, ...v }, index) => {
          this.cpylTableData.push({
            ...e,
            ...v,
            i: i + 1,
            begin: index === 0 ? this.cpylTableData.length : null,
            fabricVOList: childList,
          });
        });
      });
    },

    async getCustomerOrderInfo() {
      const { data } = await getCustomerOrderInfo({
        proOrderCustomCurtainId: this.data.proOrderId,
      });
      this.orderInfo = {
        ...data,
        customCurtainVOList: data.customCurtainVOList,
      };
      // 窗帘
      this.handleCLData(data);
      // 窗幔
      this.handleCMData(data);
      // 其他
      this.handleQTData(data);
      // 成品原料
      this.handleCPYLData(data);
    },
    handleDownload() {
      const cloneDom = document.getElementById("printPDF").cloneNode(true);
      document.getElementsByTagName("body")[0].appendChild(cloneDom);
      html2Canvas(cloneDom, { allowTaint: true }).then((canvas) => {
        let contentWidth = canvas.width;
        let contentHeight = canvas.height;
        let pageHeight = (contentWidth / 592.28) * 841.89;
        let leftHeight = contentHeight;
        let position = 0;
        let imgWidth = 595.28;
        let imgHeight = (592.28 / contentWidth) * contentHeight;
        let pageData = canvas.toDataURL("image/jpeg", 1.0);
        // console.log(pageData);

        var oA = document.createElement("a");
        oA.download = this.orderInfo.orderNo; // 设置下载的文件名，默认是'下载'
        oA.href = pageData;
        document.body.appendChild(oA);
        oA.click();
        oA.remove();

        // let PDF = new JsPDF("", "pt", "a4");
        // if (leftHeight < pageHeight) {
        //   PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
        // } else {
        //   while (leftHeight > 0) {
        //     PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
        //     leftHeight -= pageHeight;
        //     position -= 841.89;
        //     if (leftHeight > 0) {
        //       PDF.addPage();
        //     }
        //   }
        // }
        // PDF.save(`${this.orderInfo.orderNo}.pdf`);
        document.getElementsByTagName("body")[0].removeChild(cloneDom);
      });
    },
  },
};
</script>

<style scoped lang="scss">
.split-view {
  padding: 20px;
  .split-descriptions {
    font-size: 16px;
    font-weight: bold;
    ::v-deep {
      th {
        display: none;
      }
      .el-descriptions-item__cell {
        border: 1px solid rgb(50, 50, 50);
        color: rgb(96, 98, 102);
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
  .drawer-collapse {
    ::v-deep {
      .el-collapse-item__header {
        height: 65px;
        line-height: 65px;
        font-size: 16px;
      }
    }
  }
}
</style>
